package com.fs.web.base.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.baseMapper.MenuMotionMapper;
import com.fs.common.baseMapper.RoleRightMapper;
import com.fs.common.pojo.*;
import com.fs.common.vo.UnhandledEventVo;
import com.fs.common.yzMapper.CheckNoteMapper;
import com.fs.web.base.enums.CodeEnum;
import com.fs.web.base.param.SysConstant;
import com.fs.web.base.service.MenuService;
import com.fs.web.base.utils.ApplicationUtils;
import com.fs.web.base.utils.DateUtils;
import com.fs.web.base.vo.DataGrid;
import com.fs.web.base.vo.JsonResponse;
import com.fs.web.base.vo.SysPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ACE
 * @desc 菜单controller
 * @creationTime 2019-04-20 12:45
 * @projectName weixinframe
 * @packageName com.fs.web.base.controller
 */
@Slf4j
@Controller
@RequestMapping("/console/menu/rewrite")
public class MenuController {
    @Autowired
    private MenuMotionMapper menuMotionMapper;
    @Autowired
    private RoleRightMapper roleRightMapper;
    @Autowired
    private MenuService menuService;

    @Autowired
    CheckNoteMapper checkNoteMapper;

    @RequestMapping("/toConfig")
    public String toConfig(){
        return SysPath.BACK_PATH.concat("/menu/config");
    }

    //获取当前角色的菜单列表
    @ResponseBody
    @RequestMapping("/list")
    public JsonResponse list(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            List<Menu> list = (List<Menu>)ApplicationUtils.getSession().getAttribute("SESSION_CONSOLE_MENU_LIST");
            return JsonResponse.success(DataGrid.gridBuilder(list));
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 获取快捷方式列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/shortCutList")
    public JsonResponse getShortCut(){
        try {
            List<Menu> menuList = new ArrayList<>();
            List<Menu> list = (List<Menu>)ApplicationUtils.getSession().getAttribute(SysConstant.SESSION_CONSOLE_MENU_LIST);
            for (Menu m : list) {
                if (m.getShortCut() == 1) {
                    menuList.add(m);
                }
            }
            return JsonResponse.success(menuList);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 获取主页代办事件栏名称和计数
     * @return
     */
    @ResponseBody
    @RequestMapping("/unhandledEvent")
    public JsonResponse getUnhandledEvent(){
        try {
            List<UnhandledEventVo> listMap = menuService.getUnhandledEventList();
            return JsonResponse.success(listMap);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/config")
    public JsonResponse config(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            String motionJsonArray = map.get("motionJsonArray").toString();
            JSONArray jsonArray = JSONArray.parseArray(motionJsonArray);
            QueryWrapper<MenuMotion> wrapper = new QueryWrapper<>();
            wrapper.eq("menu_id",id);
            List<MenuMotion> menuMotions = menuMotionMapper.selectList(wrapper);
            if(jsonArray.size() != 0){
                Map<String,MenuMotion> objectMap = new HashMap<>();
                if(!CollectionUtils.isEmpty(menuMotions)){
                    for (MenuMotion menuMotion : menuMotions) {
                        objectMap.put(menuMotion.getMotionId(),menuMotion);
                    }
                }
                for (int i = 0; i < jsonArray.size(); i++) {
                    Motion motion = jsonArray.getObject(i, Motion.class);
                    if(!CollectionUtils.isEmpty(menuMotions)){
                        MenuMotion menuMotion = objectMap.get(motion.getId());
                        if(menuMotion != null){
                            menuMotion.setMotionOrder(motion.getMotionOrder());
                            menuMotion.setMotionName(motion.getMotionName());
                            menuMotion.setMotionIcon(motion.getMotionIcon());
                            menuMotion.setMotionCode(motion.getMotionCode());
                            menuMotionMapper.updateById(menuMotion);
                            objectMap.remove(motion.getId());
                        }else{
                            menuMotion = new MenuMotion(id,motion);
                            menuMotionMapper.insert(menuMotion);
                        }
                    }else{
                        MenuMotion menuMotion = new MenuMotion(id,motion);
                        menuMotionMapper.insert(menuMotion);
                    }
                }
                if(!CollectionUtils.isEmpty(objectMap.keySet())){
                    for (MenuMotion menuMotion : objectMap.values()) {
                        deleteMenuMotion(menuMotion);
                    }
                }
            }else{
                if(!CollectionUtils.isEmpty(menuMotions)){
                    for (MenuMotion menuMotion : menuMotions) {
                        deleteMenuMotion(menuMotion);
                    }
                }
            }
            return JsonResponse.success("授权成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    private void deleteMenuMotion(MenuMotion menuMotion){
        QueryWrapper<RoleRight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_motion_id",menuMotion.getId());
        List<RoleRight> roleRights = roleRightMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(roleRights)){
            for (RoleRight roleRight : roleRights) {
                roleRightMapper.deleteById(roleRight.getId());
            }
        }
        menuMotionMapper.deleteById(menuMotion.getId());
    }
}
